{extend name="admin@public/basic" /}
{block name="style"}{/block}
<!-- <link rel="stylesheet" href="__STATIC__/css/admin/public.css" media="all"/> -->

{block name="cotent"}
<link rel="stylesheet" href="__STATIC__/css/admin/public.css" media="all"/>
<style>
    .tip{
        color: red;
    }
    .gray-tip {
        font-family: sans-serif !important;
        font-weight: 10 !important;
        margin-top: 5px !important;
        color: #A8A8A8 !important;
    }
    .layui-table td, .layui-table th {
        padding: 9px 4px;
    }
    .newupload{
        width: 100px !important;
        height: 40px !important;
        background: url(__STATIC__/image/admin/nopic.png) no-repeat;
        background-size: 100% 100%;
        border:none;
        overflow: hidden;
        cursor: pointer;
        position: relative;
        text-align: center;
    }
    .newInput{
        width: 80px !important;
    }
    .webuploader-container input {
        width: 100%;
        height: 100%;
    }

    .webuploader-pick {
        width: 100%;
        height: 100%;
        border: 1px solid blue;
    }
    .thumbBox {
        position: relative;
    }
    .thumbBox input{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        cursor: pointer;
    }
</style>
<form id="form" class="layui-form" style="width:80%;">
    <div class="layui-tab">
        <ul class="layui-tab-title">
            <li class="layui-this">基本信息</li>
            <li>小程序太阳码图片</li>

        </ul>
        <div class="layui-tab-content ">
            <!--基本信息-->
            <div class="layui-tab-item layui-show">
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">简称</label>
                    <div class="layui-input-block">
                        <input type="text" name="short" class="layui-input short" lay-verify="required" value="{$data.short|default=''}" placeholder="请输入应用简称 如cloud">
                    </div>
                </div>

                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" class="layui-input name" lay-verify="required" value="{$data.name|default=''}" placeholder="请输入应用名称">
                    </div>
                </div>
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">CRM地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="manager_link" class="layui-input manager_link" lay-verify="required" value="{$data.manager_link|default=''}" placeholder="请输入访问地址">
                    </div>
                </div>
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">接口地址</label>
                    <div class="layui-input-block">
                        <input type="text" name="api_host" class="layui-input api_host" lay-verify="required" value="{$data.api_host|default=''}" placeholder="请输入接口地址https://xxxxx/">
                    </div>
                </div>
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">描述</label>
                    <div class="layui-input-block">
                        <textarea name="desc" placeholder="描述" class="layui-textarea desc">{$data.desc|default=''}</textarea>
                    </div>
                </div>
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">状态</label>
                    <div class="layui-input-block status">
                        {if !empty($data)}
                        <input type="radio" name="status" value="1" title="待发布" {if condition="$data.status == 1"}checked{/if}>
                        <input type="radio" name="status" value="2" title="正常" {if condition="$data.status == 2"}checked{/if}>
                        <input type="radio" name="status" value="3" title="已停用" {if condition="$data.status == 3"}checked{/if}>
                        {else}
                        <input type="radio" name="status" value="1" title="待发布">
                        <input type="radio" name="status" value="2" title="正常" checked>
                        <input type="radio" name="status" value="3" title="已停用" >
                        {/if}
                    </div>
                </div>



                {if !empty($data)}
                <input type="hidden" class="id" name="id" value="{$data.id|default=''}">
                {/if}
            </div>

            <!-- 规格 -->
            <div class="layui-tab-item">
                <div class="layui-form-item layui-row layui-col-xs12">
                    <label class="layui-form-label">上传图片</label>
                    <div class="layui-col-md12" style="padding-left: 34px">
                        <button class="layui-btn layui-btn-primary" type="button" onclick="addScale()">添加图片 </button>
                        <!--<label class="tip">请先选择商品</label>-->
                        <label class="gray-tip" style="line-height:40px;">推荐尺寸:140px*140px</label>
                        <table class="layui-table" lay-skin="nob" id="table-head">
                            <thead>
                            <tr id="tr1">
                                <th data-name="norms_pic" >小程序太阳码图片</th>
                                <!--<th data-name="norms_name">名称</th>-->
                                <th >操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            {if !empty($data)}
                            {foreach $data.weapp_qrcode as $k => $v}
                            <tr id='speci{$k}'>
                                <td style='position:relative;overflow:hidden'>
                                    <input type='hidden' id='data_photo{$k}' name='norms_pic' value="{$v.norms_pic}" />
                                    <div id='fileList{$k}' class='uploader-list' style='float:right'></div>
                                    <div id='imgPicker{$k}' style='opacity: 0.0;margin-left: 10px;position:absolute;top:0;left:0;width:100%;height:100%'>选择图片</div>
                                    <img id='img_data{$k}' style='float:left;width:100px;height: 50px;' src='{$v.norms_pic}'/></td>
                                <td><button type='button' {if empty($k)}disabled{/if} class='layui-btn layui-btn-sm' onclick='del_scale(this)'>删除</button></td>
                            </tr>
                            {/foreach}
                            {/if}
                            </tbody>
                        </table>
                        <label class='tip'></label>
                    </div>
                </div>

            </div>
        </div>
    </div>


    <div class="layui-form-item layui-row layui-col-xs12">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-sm" lay-submit="" id="addUser">确定</button>
            <button type="reset" class="layui-btn layui-btn-sm layui-btn-primary">取消</button>
        </div>
    </div>
    </div>
</form>

{/block}

{block name="script"}
<script type="text/javascript" src="__STATIC__/layuicms/layui/layui.js"></script>
<script type="text/javascript" src="__STATIC__/plugs/webuploader.min.js"></script>

<script>

    //若为新增时生成一次规格
    $(function(){
        {if empty($data)}addScale();dealPicture();{else/}dealPicture();{/if}
    })



    layui.use(['form','layer','layedit','upload','element'],function(){
        var form = layui.form
        layer = parent.layer === undefined ? layui.layer : top.layer,
            laypage = layui.laypage,
            upload = layui.upload,
            layedit = layui.layedit,
            element = layui.element,
            $ = layui.jquery;

        //用于同步编辑器内容到textarea
        layedit.sync(editIndex);
        layedit.sync(editIndex2);

        //一些事件监听
        element.on('tab(demo)', function (data) {
            console.log(data);
        });

        /**
         * 新增以及编辑后台用户
         */
        $("#addUser").click(function () {
            layedit.sync(editIndex);
            layedit.sync(editIndex2);
            var url = '{if empty($data)}{:url("$thisClass/add")}{else/}{:url("$thisClass/edit")}{/if}';

            var data = {
                id: $(".id").val(),
                name: $(".name").val(),
                short: $(".short").val(),
                status: $('input[name="status"]:checked').val(),
                //image: $('input[name="image"]').val(),
                manager_link: $(".manager_link").val(),
                desc: $(".desc").val(),
                api_host: $(".api_host").val(),
                //meal_content: $("#meal_content").val(),
                //server_content: $("#server_content").val(),
            };
            // 处理规格信息
            var speci = [];
            var tdnode = $("#tr1").find("th");
            var index = $("#table-head").find("tbody").find("tr").length;
            for(var i=0;i<index;i++){
                var speciOne = {};
                var trData = $("#speci"+i);
                var trId = $("#speci"+i).find("input[name='id']").val();
                var trMealid = $("#speci"+i).find("input[name='meal_id']").val()
                if(trId!='' && trId != undefined && trId !=null){
                    speciOne['id'] = trId;
                    speciOne['meal_id'] = trMealid;
                }
                for(var j=0;j<tdnode.length-1;j++){
                    var tdData = $(trData).find("input[name='"+tdnode[j].dataset.name+"']").val();
                    speciOne[tdnode[j].dataset.name] = tdData;
                }
                speci.push(speciOne);
            }
            data['speci']=speci;

            $.ajax({
                url: url,
                method:"POST",
                data: data,
                success:function(res){
                    console.log(res);
                    if(res.code ==1){
                        layer.msg(res.msg,{icon: 1})
                        setTimeout(function(){
                            //刷新父页面
                            parent.location.reload();
                        },500);

                    }else{
                        layer.msg(res.msg);
                    }
                }
            })
            return false;
        });


        //创建一个编辑器,套餐详情
        var editIndex = layedit.build('meal_content',{
            height : 535,
            uploadImage : {
                url : "{:url('api/Upload/uploadRichTextFile')}"
            }
        });
        //创建一个编辑器,套餐详情
        var editIndex2 = layedit.build('server_content',{
            height : 535,
            uploadImage : {
                url : "{:url('api/Upload/uploadRichTextFile')}"
            }
        });
        form.render();

    })
    // 添加规格
    function addScale() {
        var tdnode = $("#tr1").find("th");
        console.log(tdnode[0].dataset.name);
        var index = $("#table-head").find("tbody").find("tr").length;
        console.log(index);
        var html='';
        if (tdnode.length-1 > 0) {
            html += "<tr id='speci"+index+"'><td style='position:relative;overflow:hidden'><input type='hidden' id='data_photo" + index + "' name='" + tdnode[0].dataset.name + "' />"
                +"<div id='fileList" + index + "' class='uploader-list' style='float:right'></div>"
                +"<div id='imgPicker" + index + "' style='opacity: 0.0;margin-left: 10px;position:absolute;top:0;left:0;width:100%;height:100%'>选择图片</div>"
                +"<img id='img_data" + index + "' style='float:left;width:100px;height: 50px;' src='__STATIC__/image/admin/nopic.png'/></td>";

            for (var i = 1; i < tdnode.length - 1; i++) {
                console.log(tdnode[i].style.display)
                if (tdnode[i].style.display == 'none') {
                    continue;
                }
                console.log(tdnode[i].dataset.val);
                if (tdnode[i].dataset.val >= 0) {
                    html += "<td><input  value='" + tdnode[i].dataset.val + "' name='" + tdnode[i].dataset.name + "' type='text' class='layui-input newInput' /></td>";
                } else {
                    html += "<td><input  value='' name='" + tdnode[i].dataset.name + "' type='text' class='layui-input newInput' /></td>";
                }

            }
            html += "<td><button type='button' class='layui-btn layui-btn-sm' onclick='del_scale(this)'>删除</button></td>";
            html += "</tr>";
            $("#table-head").find("tbody").append(html);
            dealPicture();
        }

    }
    // 删除规格
    function del_scale(obj) {
        var tr = obj.parentNode.parentNode;
        var tbody = tr.parentNode;
        var index = $("#table-head").find("tbody").find("tr").length;
        console.log(index);
        if(index>1){
            tbody.removeChild(tr);
        }

    }

    // 上传图片
    function uploadFile(inputName){
        var data = new FormData();
        $.each($('input[name="'+inputName+'"]')[0].files, function(i, file) {
            data.append('file', file);

        });
        console.log(data.get(inputName))
        //清空图片
        $('#'+inputName).val('');
        //提交数据
        $.ajax({
            url: "{:url('api/Upload/uploadFile')}",
            type: 'POST',
            data: data,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            // dataType: 'json',
            success: function(res) {
                if (res.code == 1000) {
                    $('.thumbImg').attr('src',res.data.all_url);
                    $("input[name='image']").val(res.data.url);
                }
            },
            error: function(returndata) {
                parent.layer.msg('数据异常', {
                    icon: 2,
                    time: 2000
                });
                return false;
            }
        });
    }

    function dealPicture(){
        var div = $("div[id^=fileList]");
        var uploader;
        div.each(function(index){

            var $list = $('#fileList' + index);
            //上传图片,初始化WebUploader
            uploader = WebUploader.create({
                auto: true, // 选完文件后，是否自动上传。
                swf: '/static/admin/webupload/Uploader.swf', // swf文件路径
                server: "{:url('api/Upload/uploadFile')}", // 文件接收服务端。
                duplicate: true, // 重复上传图片，true为可重复false为不可重复
                pick: '#imgPicker' + index, // 选择文件的按钮。可选。

                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/jpg,image/jpeg,image/png'
                },
                'onUploadSuccess': function (file, data, response) {
                    var src = data.data.all_url;
                    var title = data.data.url;
                    $("#data_photo" + index).val(title);
                    $("#img_data" + index).attr('src', src).show();
                }
            });

            uploader.on('fileQueued', function (file) {

            });

            // 文件上传成功
            uploader.on('uploadSuccess', function (file) {
                //$('#' + file.id).find('p.state').text('上传成功！');
            });

            // 文件上传失败，显示上传出错。
            uploader.on('uploadError', function (file) {
                //$('#' + file.id).find('p.state').text('上传出错!');
            });
        });

    }


</script>
{/block}
